﻿using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using TpExtensions;
using Microsoft.Office.Interop.Excel;
using TpBaseObjects.Properties;
using TpLogger;
using myOffice = Microsoft.Office.Interop;

namespace TpBaseObjects.Base {
    public abstract class AbstractExcelTools {

        #region Members

        private Logger log;
        protected Microsoft.Office.Interop.Excel.Application exApp;
        protected bool excelIsStarted;
        protected int startRow = 3;
        protected bool debugMode = false; //Standard = false!!!!!!!!

        #endregion

        #region Constructor

        public AbstractExcelTools() {
            //if(DateTime.Now.Hour > 2 & DateTime.Now.Hour < 6) {
            //    debugMode = false;
            //}

            Settings.Default.Reset();
            Settings.Default.Reload();
            log = new Logger();
            excelIsStarted = ExcelIsStarted();
            exApp = GetExcelApplication();

            
        }

        #endregion

        #region Properties

        protected bool DebugMode {
            get { return debugMode; }
        }

        protected string ErrorFileName {
            get { return Path.Combine(MaPath, Settings.Default.DateiExportFehler); }
        }

        public string MaPath {
            get {
                if(debugMode) {
                    return Path.Combine(Settings.Default.MaPath.Replace(@"\Ma\", @"\Ma\12\Testing\"), DateTime.Today.AddDays(-1).Year.ToString().Right(2) + @"\");
                } else {
                    return Path.Combine(Settings.Default.MaPath, DateTime.Today.AddDays(-1).Year.ToString().Right(2) + @"\");
                }
            }
        }

        public string Jesu {
            get {
                if(debugMode) {
                    return Settings.Default.DateiJesu.Replace(@"\Ma\", @"\Ma\Testing\");
                } else {
                    return Settings.Default.DateiJesu;
                }
            }
        }

        public string Lesu {
            get {
                if(debugMode) {
                    return Settings.Default.DateiLesu.Replace(@"\Ma\", @"\Ma\Testing\");
                } else {
                    return Settings.Default.DateiLesu;
                }
            }
        }

        public string TpInternFileNames {
            get { return Settings.Default.TpInternFileNames; }
        }

        #endregion

        #region Methods

        protected void CloseAllWorkbooks(bool save) {
            try {
                log.Add("Begin CloseAllWorkbooks");
                foreach(Workbook wb in exApp.Workbooks) {
                    wb.Close(save);
                }
                log.Add("End CloseAllWorkbooks");
            } catch(Exception ex) {
                log.Add("CloseAllWorkbooks", ex);
            }
        }

        protected void SetApplication(Microsoft.Office.Interop.Excel.Application exApp, bool state) {
            exApp.ScreenUpdating = state;
            exApp.EnableEvents = state;
            exApp.DisplayAlerts = state;
        }

        protected void SortSheetRows(Worksheet sh, int startRow, int lastRow, string[] columns) {
            SortSheetRows(sh, startRow, lastRow, columns, Extensions.tpSortOrder.Up);
        }

        protected void SortSheetRows(Worksheet sh, int startRow, int lastRow, string[] columns, Extensions.tpSortOrder sortOrder) {
            try {
                Range[] ranges = new Range[columns.Length];

                for(int i = 0; i < columns.Length; i++) {
                    ranges[i] = sh.Range[columns[i] + (startRow).ToString() + ":" + columns[i] + (lastRow).ToString()];
                }

                sh.Sort.SortFields.Clear();
                foreach(Range r1 in ranges) {
                    string t1 = r1.Address;
                    sh.Sort.SortFields.Add(Key:r1, SortOn:XlSortOn.xlSortOnValues, Order:(sortOrder == Extensions.tpSortOrder.Up ? XlSortOrder.xlAscending : XlSortOrder.xlDescending), DataOption:XlSortDataOption.xlSortNormal);
                }

                Range setRange = sh.Rows[startRow.ToString() + ":" + lastRow.ToString()];
                int test1 = sh.Sort.SortFields.Count;

                setRange.Select();

                sh.Sort.SetRange(setRange);
                sh.Sort.Header = XlYesNoGuess.xlGuess;
                sh.Sort.MatchCase = false;
                sh.Sort.Orientation = XlSortOrientation.xlSortColumns;
                sh.Sort.SortMethod = XlSortMethod.xlPinYin;
                sh.Sort.Apply();
            } catch(Exception ex) {
                log.Add("SortSheetRows", ex);
            }
        }

        abstract public void SetTpUser();

        #endregion

        #region Functions

        protected bool ExcelIsStarted() {
            try {
                Process[] procs = Process.GetProcesses();
                foreach(Process proc in procs) {
                    if(proc.ProcessName.IndexOf("EXCEL") > -1) {
                        return true;
                    }
                }

            } catch(Exception ex) {
                log.Add("GetExcelApplication", ex);
            }
            return false;
        }

        protected myOffice.Excel.Application GetExcelApplication() {
            try {
                Process[] procs = Process.GetProcesses();
                foreach(Process proc in procs) {
                    if(proc.ProcessName.IndexOf("EXCEL") > -1) {
                        return (myOffice.Excel.Application)Marshal.GetActiveObject("Excel.Application");
                    }
                }
                return new myOffice.Excel.Application();
            } catch(Exception ex) {
                log.Add("GetExcelApplication", ex);
            }
            return null;
        }

        protected bool WorkBookIsLoaded(string workBookName) {
            foreach(Workbook wb in exApp.Workbooks) {
                if(wb.Name.Contains(workBookName)) {
                    return true;
                }
            }
            return false;
        }

        #endregion

    }
}
